package com.kjj.user.controller;

import com.kjj.basic.util.AjaxResult;
import com.kjj.basic.util.VerifyCodeUtils;
import com.kjj.user.dto.SMSCodeDto;
import com.kjj.user.service.IVerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @GetMapping("/img")
    public void imgeCode(HttpSession session, HttpServletResponse response){

        //产生验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);

        //存放session
        session.setAttribute("verifyCode",verifyCode);

        //把验证码最为图片响应给客户端
        try {
            ServletOutputStream os = response.getOutputStream();
            VerifyCodeUtils.outputImage(200,40,os,verifyCode);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Autowired
    private IVerifyCodeService verifyCodeService;
    @GetMapping("/img/{key}")
    public AjaxResult getImgeCode(@PathVariable("key") String key){
        try {
            String base64ImageCode = verifyCodeService.getImageCode(key);
            return AjaxResult.me().setData(base64ImageCode);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取图片验证码失败!" + e.getMessage());
        }
    }
    @PostMapping("/sendSmsCode")
    public AjaxResult sendSmsCode(@RequestBody SMSCodeDto smsCodeDto){
        try {
            return verifyCodeService.sendSmsRegisterCode(smsCodeDto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取图片验证码失败!" + e.getMessage());
        }
    }
    @PostMapping("/sendLoginSmsCode")
    public AjaxResult sendLoginSmsCode(@RequestBody SMSCodeDto smsCodeDto){
        try {
            return verifyCodeService.sendSmsLoginCode(smsCodeDto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取图片验证码失败!" + e.getMessage());
        }
    }
}
